/**
 * 
 */
package net.sf.cldsql.dj.utl;

import java.util.List;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class Script {
    private ScriptEngine engine;

    public Script(String engineName) {
        ScriptEngineManager sem = new ScriptEngineManager();
        this.engine = sem.getEngineByName(engineName);
    }
    
    public Object run (String statement) throws Exception {
        try {
            return engine.eval(statement);
        } catch (ScriptException ex) {
            throw ex;
        }
    }
    
    public static String listEngines () {
        ScriptEngineManager sem = new ScriptEngineManager();
        List list = sem.getEngineFactories();
        ScriptEngineFactory f;
        String ret = "";
        for (int i = 0; i < list.size(); i++) {
          f = (ScriptEngineFactory) list.get(i);
          String engineName = f.getEngineName();
          String engineVersion = f.getEngineVersion();
          String langName = f.getLanguageName();
          String langVersion = f.getLanguageVersion();
          ret += engineName + " " + engineVersion 
                  + " " + langName + " " + langVersion + "\n";
          @SuppressWarnings("unused")
          String statement = f.getOutputStatement("\"hello, world\"");
          @SuppressWarnings("unused")
          ScriptEngine e = f.getScriptEngine();
        }
        return ret;
    }
    
}
